package cn.itcast.n8;

import cn.itcast.n2.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

@Slf4j(topic = "c.TestTimer")
public class TestTimer {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        final ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
//        pool.schedule(()->{
//            log.debug("task1...");
//            try {
//                int i = 1/0;
//            }catch (Exception e){
//                log.error("error:",e);
//            }
//        },1,TimeUnit.SECONDS);

        final ExecutorService pool = Executors.newFixedThreadPool(1);
        final Future<Boolean> task1 = pool.submit(() -> {
            log.debug("task1");
            int i = 1 / 0;
            return true;
        });

        log.debug("result:{}",task1.get());

    }

    private static void method3(ScheduledExecutorService pool) {
        log.debug("start");
        pool.scheduleAtFixedRate(()->{
            log.debug("running");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },1,1,TimeUnit.SECONDS);

//        pool.scheduleWithFixedDelay(()->{
//            log.debug("runnning...");
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        },1,1,TimeUnit.SECONDS);
    }

    private static void method2(ScheduledExecutorService pool) {
        pool.schedule(() -> {
            log.debug("task1");
//            Sleeper.sleep(2);
            int i = 1 / 0;
        }, 1, TimeUnit.SECONDS);

        pool.schedule(() -> {
            log.debug("task2");
        }, 1, TimeUnit.SECONDS);
    }

    private static void method1() {
        final Timer timer = new Timer();
        final TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 1");
//                Sleeper.sleep(2);
//                int i = 1/0;
            }
        };

        final TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task 2");
            }
        };

        log.debug("start...");
        timer.schedule(task1, 1000);
//        timer.schedule(task2, 1000);
        timer.schedule(task2, 1000,2000);
    }
}
